package com.android.qjpmc.widget.utils;

import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SpanTextUtil {

    /**
     * 获取可点击文本的文本串
     * @param content 文本内容
     * @param findStrs 要从content中找出得文本串
     * @param colorStr findStrs文本需要设置的颜色
     * @param callback
     * @return
     */
    public static CharSequence getSpanText(String content, String[] findStrs, String colorStr, ICallback callback) {
        SpannableStringBuilder builder = new SpannableStringBuilder(content);
        if (findStrs == null || findStrs.length == 0) {
            return builder;
        }
        for (String findStr : findStrs) {
            setClickableSpan(findStr, colorStr, builder, callback);
        }
        return builder;
    }

    private static void setClickableSpan(final String findStr, String colorStr,
                                         final SpannableStringBuilder clickableHtmlBuilder, final ICallback callback) {
        if (findStr == null || clickableHtmlBuilder == null) {
            return;
        }
        Pattern pattern = Pattern.compile(findStr);
        Matcher matcher = pattern.matcher(clickableHtmlBuilder);
        if (!matcher.find()) {
            return;
        }
        int start = matcher.start();
        int end = matcher.end();
        ClickableSpan clickableSpan = new ClickableSpan() {
            public void onClick(View view) {
                if (callback != null) {
                    callback.onClick(findStr);
                }
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                //当传入true时超链接下会有一条下划线
                ds.setUnderlineText(false);
            }
        };
        //设置超链接文本的颜色
        int color = Color.WHITE;
        try {
            color = Color.parseColor(colorStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        clickableHtmlBuilder.setSpan(new ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        clickableHtmlBuilder.setSpan(clickableSpan, start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
    }

    public interface ICallback {

        void onClick(String findStr);

    }

}
